package io.lvdaxian.handwriting.notify;

class Message {
  private String message;
  private boolean hasNewMessage = false;
  
  public synchronized void setMessage(String message) {
    while (hasNewMessage) {
      try {
        wait(); // 如果有新消息，则等待
      } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
      }
    }
    this.message = message;
    hasNewMessage = true;
    notify(); // 通知等待的线程
  }
  
  public synchronized String getMessage() {
    // hasNewMessage 默认就是 false。所以第一次进行while循环中
    while (!hasNewMessage) {
      try {
        System.out.println("此时 被卡住了 ...");
        wait(); // 如果没有新消息，则等待
        System.out.println("此时的 wait() 已经被唤醒了");
      } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
      }
    }
    hasNewMessage = false;
    notify(); // 通知等待的线程
    return message;
  }
}

public class Main {
  public static void main(String[] args) throws InterruptedException {
    Message message = new Message();
    
    new Thread(() -> {
      String receivedMessage = message.getMessage();
      System.out.println("Received message: " + receivedMessage);
    }).start();
    
    Thread.sleep(10);
    
    new Thread(() -> {
      message.setMessage("Hello from producer!");
    }).start();
  }
}
